package com.ali.service.impl;

import com.ali.common.BeanCopyUtil;
import com.ali.common.UUIDUtil;
import com.ali.dao.OrderMapper;
import com.ali.dao.PayMapper;
import com.ali.dto.OrderInfo;
import com.ali.dto.PayInfo;
import com.ali.entity.Order;
import com.ali.entity.Pay;
import com.ali.service.OrderService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private PayMapper payMapper;

    @Override
    public void addOrderAndPay(Map<String, Object> param) {
        Order order = new Order();
        order.setOrderNo(UUIDUtil.getUUID());
        order.setStatus(1);
        orderMapper.add(order);

        Pay pay = new Pay();
        pay.setOrderId(order.getId());
        pay.setPayNo((String) param.get("payno"));
        pay.setPayMoney(Integer.parseInt((String) param.get("paymoney")));
        payMapper.add(pay);
    }

    @Override
    public void update(Map<String, Object> param) {
        orderMapper.update(param);
    }

    @Override
    public void delete(Map<String, Object> param) {
        orderMapper.delete(param);
    }

    @Override
    public List<OrderInfo> getAll(Map<String, Object> param) {
        int start = Integer.parseInt((String) param.get("start"));
        int size = Integer.parseInt((String) param.get("size"));
        param.put("start", (start - 1) * size);
        param.put("size", size);
        List<Order> orders = orderMapper.queryOrder(param);
        return BeanCopyUtil.copyListProperties(orders, OrderInfo::new);
    }

    @Override
    public OrderInfo getById(Map<String, Object> param) {
        List<Order> orders = orderMapper.queryOrderById(param);
        List<OrderInfo> orderInfos = BeanCopyUtil.copyListProperties(orders, OrderInfo::new);
        if (CollectionUtils.isEmpty(orderInfos)) {
            return null;
        }

        OrderInfo orderInfo = orderInfos.get(0);

        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("orderId", param.get("id"));
        List<Pay> pays = payMapper.queryPay(queryParam);
        List<PayInfo> payInfos = BeanCopyUtil.copyListProperties(pays, PayInfo::new);
        orderInfo.setPayInfos(payInfos);
        return orderInfo;
    }
}
